#!/usr/bin/env python3
"""
API文档生成MCP工具发布脚本
"""

import os
import subprocess
import sys

def run_command(*args):
    """运行命令并检查返回码"""
    print(f"运行命令: {' '.join(args)}")
    result = subprocess.run(args, capture_output=True, text=True, check=True)
    print(result.stdout)
    return result

def clean_directory(path):
    """清理目录"""
    if os.path.exists(path):
        run_command("rmdir", "/s", "/q", path)

def build_package():
    """构建Python包"""
    print("开始构建Python包...")
    # 清理之前的构建
    clean_directory("build")
    clean_directory("dist")
    clean_directory("api_doc_mcp_server.egg-info")
    
    # 构建新包
    run_command("c", "setup.py", "sdist", "bdist_wheel")
    print("包构建完成!")

def check_package():
    """检查包"""
    print("检查包...")
    run_command("twine check dist/*")
    print("包检查完成!")

def upload_to_test_pypi():
    """上传到TestPyPI"""
    print("上传到TestPyPI...")
    run_command("twine upload --repository testpypi dist/*")
    print("已上传到TestPyPI!")

def upload_to_pypi():
    """上传到PyPI"""
    print("上传到PyPI...")
    run_command("twine upload dist/*")
    print("已上传到PyPI!")

def main():
    """主函数"""
    print("API文档生成MCP工具发布脚本")
    print("=" * 40)
    
    if not os.path.exists("dist"):
        build_package()
    
    check_package()
    
    print("\n选择操作:")
    print("1. 上传到TestPyPI (测试)")
    print("2. 上传到PyPI (正式发布)")
    print("3. 仅构建包")
    
    choice = input("请输入选择 (1-3): ").strip()
    
    if choice == "1":
        upload_to_test_pypi()
    elif choice == "2":
        confirm = input("确认上传到PyPI? (y/N): ").strip().lower()
        if confirm == "y":
            upload_to_pypi()
        else:
            print("已取消上传")
    elif choice == "3":
        print("包已构建完成，位于 dist/ 目录")
    else:
        print("无效选择")

if __name__ == "__main__":
    main()